package com.hyacinth.web.ui.easyui;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.hyacinth.core.sysmgr.domain.SysMenu;
import com.hyacinth.web.ui.easyui.vo.Tree;

public class TreeFormatter {
	
	public String getMenuData(List<SysMenu> allMenus, List<SysMenu> roleMenus) {
		StringBuilder ids = new StringBuilder();
		for(SysMenu m : roleMenus) {
			ids.append(m.getId()).append(",");
		}
		List<Tree> trees = new ArrayList<Tree>();
		for(SysMenu m : allMenus) {
			Tree tree = new Tree(m.getId(), m.getName(), m.getPid());
			trees.add(tree);
		}
		return getJson(getTreeList(trees,1L,ids.toString()));
	}
	
	private String getJson(List<Tree> list) {
		String[] fields = {"text","id","state","checked","children"};
		SimplePropertyPreFilter spp = new SimplePropertyPreFilter(Tree.class, fields);
		return JSON.toJSONString(list, spp, SerializerFeature.DisableCircularReferenceDetect);
	}
	
	private List<Tree> getTreeList(List<Tree> all, Long id, String ids) {
		List<Tree> list = new ArrayList<Tree>();
		for(Tree t1 : all) {
			Long _id = t1.getId();
			if(_id==id) {
				String idStr = Long.valueOf(_id)+",";
				if(ids.indexOf(idStr)>=0) {
					t1.setChecked(true);
				}
				for(Tree t2 : all) {
					Long _pid = t2.getPid();
					if(_pid==_id) {
						t1.addChildren(getTreeList(all, t2.getId(), ids));
					}
				}
				t1.setPid(null);
				list.add(t1);
			}
		}
		return list;
	}
}
